import { Directive, OnInit, OnDestroy, OnChanges, SimpleChanges, Input,
  ElementRef, HostListener, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import {User} from './user';
import {DashboardComponent} from './dashboard/dashboard.component';

@Directive({
  selector: '[appSpy]'
})
export class SpyDirective implements OnInit, OnDestroy, OnChanges {

  private tagName: string;
  @Input() user: User;
  @HostListener('mouseenter') onMouseEnter() {
    // this.log(`${this.tagName} component mouse enter`);
    const domElement = this.el.nativeElement;
    const childElement = domElement ? domElement.children[0] : null;
    if (childElement) {
      childElement.style.backgroundColor = '#444';
      childElement.style.color = 'orange';
    }
  }@HostListener('mouseleave') onMouseLeave() {
    // this.log(`${this.tagName} component mouse leave`);
    const domElement = this.el.nativeElement;
    const childElement = domElement ? domElement.children[0] : null;
    if (childElement) {
      childElement.style.backgroundColor = '';
      childElement.style.color = '';
    }
  }
  constructor(private el: ElementRef,
    private componentFactoryResolver: ComponentFactoryResolver,
    public viewContainerRef: ViewContainerRef) {
    this.tagName = this.el.nativeElement.tagName.toLowerCase();
  }

  ngOnInit() {
    this.log(`${this.tagName} component for ${this.user ? this.user.name : ''} onInit`);
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DashboardComponent);
    this.viewContainerRef.clear();
    const componentRef = this.viewContainerRef.createComponent(componentFactory);
    const cponent = <DashboardComponent>componentRef.instance;
  }
  ngOnDestroy() {
    this.log(`${this.tagName} component for ${this.user ? this.user.name : ''} onDestroy`);
  }
  ngOnChanges(changes: SimpleChanges) {
    for (const propName in changes) {
      if (changes.hasOwnProperty(propName)) {
        const chng = changes[propName];
        const cur  = JSON.stringify(chng.currentValue);
        const prev = JSON.stringify(chng.previousValue);
        this.log(`${this.tagName} {${propName}} changed, currentValue = ${cur}, previousValue = ${prev}`);
      }
    }
  }
  private log(logText: string) {
    console.log(logText);
  }
}
